<template>
    <div class="app-container">
        <h3>航线列表</h3>
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item label="航线名称" prop="fpName">
                <el-input v-model="queryParams.fpName" placeholder="航线名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="日期范围" prop="dateRange">
                <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery" />
            </el-form-item>
            <el-form-item label="航线类型" prop="fpType" style="width: 260px;">
                <el-select v-model="queryParams.fpType" placeholder="请选择航线类型" clearable @change="handleQuery">
                    <el-option v-for="dict in flight_plans_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />

                </el-select>
            </el-form-item>
            <el-form-item label="负载型号" prop="hailerId" style="width: 260px;">
                <el-select v-model="queryParams.hailerId" placeholder="请选择负载型号" clearable @change="handleQuery">
                    <el-option v-for="item in hailerList" :key="item.hiId" :label="item.hiName" :value="item.hiId" />
                </el-select>
            </el-form-item>
            <el-form-item label="无人机型号" prop="droneId">
                <el-input v-model="queryParams.droneId" placeholder="请输入无人机型号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="行政区" prop="administrativeRegion">
                <el-input v-model="queryParams.administrativeRegion" placeholder="请输入行政区" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain @click="handleAdd" v-hasPermi="['flightplans:plans:add']">创建航线
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain @click="triggerFileInput" v-hasPermi="['flightplans:plans:import']">导入航线
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain @click="handleTagManagement"
                    v-hasPermi="['flightplans:plans:tagManagement']">标签管理
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <div v-for="(monthData, month) in groupedPlans" :key="month" class="month-group">
            <h3>{{ month }}</h3>
            <el-row :gutter="20">
                <el-col :span="8" v-for="(item, index) in monthData" :key="index" :xs="24" :sm="12" :md="6" :lg="6"
                    :xl="6" class="card-col">
                    <el-card shadow="hover" class="plan-card">
                        <template #header>
                            <div class="card-header">
                                <span>{{ item.fpName }}</span>
                                <div class="operation">
                                    <el-button link type="primary" icon="Edit" @click="handleUpdate(item)"
                                        v-hasPermi="['flightplans:plans:edit']">修改</el-button>
                                    <el-button link type="primary" icon="Delete" @click="handleDelete(item)"
                                        v-hasPermi="['flightplans:plans:remove']">删除</el-button>
                                </div>
                            </div>
                        </template>
                        <div class="card-content">
                            <p><span class="label">主键：</span>{{ item.fpId }}</p>
                            <p><span class="label">负载型号：</span>{{ item.hailerName }}</p>
                            <p><span class="label">无人机型号：</span>{{ item.droneName }}</p>
                            <p><span class="label">所属机构：</span>{{ item.hiDeptName }}</p>
                            <p><span class="label">创建人：</span>{{ item.createBy }}</p>
                            <p>
                                <span class="label">航线类型：</span>
                                <dict-tag :options="flight_plans_type" :value="item.fpType" />
                            </p>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改航线列表对话框 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <el-form ref="plansRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="formSpan">
                        <el-form-item label="航线名称" prop="fpName">
                            <el-input v-model="form.fpName" placeholder="请输入飞行计划的名称，不能为空" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog :title="'导入航线'" v-model="uploadDialogVisible" width="600px">
            <el-upload class="upload-demo" drag multiple accept=".kmz" :headers="upload.headers" :action="upload.url"
                :on-success="handleSuccess" :on-error="handleError">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    Drop file here or <em>click to upload</em>
                </div>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirmUpload">确定并上传</el-button>
                    <el-button @click="uploadDialogVisible = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <div v-if="loading1" class="overlay">
            正在上传，请稍候...
        </div>

    </div>
</template>

<script setup name="Plans">
import {
    listPlans,
    getPlans,
    delPlans,
    addPlans,
    updatePlans,
    addUpload
} from "@/api/flightplans/plans";
import { listHailer } from "@/api/equipment/hailer";
import useUserStore from '@/store/modules/user'
const hiDeptName = useUserStore().deptName


const { proxy } = getCurrentInstance();
const { flight_plans_type } = proxy.useDict('flight_plans_type');

const plansList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const formSpan = ref(12);
//全屏遮罩层
const loading1 = ref(false);

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 12,
        fpName: null,
        startTime: null,
        endTime: null
    },
    rules: {
        fpName: [
            {
                required: true, message: "飞行计划的名称，不能为空不能为空", trigger: "blur"
            }
        ],
    }
})
    ;

const { queryParams, form, rules } = toRefs(data);

const uploadDialogVisible = ref(false);

const hailerList = ref([]);

function fetchHailerList() {
    listHailer({}).then(response => {
        hailerList.value = response.rows;
        console.log(hailerList.value)
    }).catch(error => {
        console.error('Failed to fetch hailer list:', error);
    });
}

fetchHailerList();

const groupedPlans = computed(() => {
    return plansList.value.reduce((acc, plan) => {
        const month = plan.createTime.slice(0, 7); // 提取年月
        if (!acc[month]) {
            acc[month] = [];
        }
        acc[month].push(plan);
        return acc;
    }, {});
});

/** 查询航线列表列表 */
function getList() {
    loading.value = true;
    if (queryParams.value.dateRange) {
        queryParams.value.startTime = new Date(queryParams.value.dateRange[0]).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' });
        queryParams.value.endTime = new Date(queryParams.value.dateRange[1]).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' });
    }
    console.log(queryParams.value);
    listPlans(queryParams.value).then(response => {
        plansList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        fpId: null,
        fpName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDeleted: null
    };
    proxy.resetForm("plansRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.fpId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    form.value.hiDeptName = hiDeptName;
    title.value = "添加航线列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _fpId = row.fpId || ids.value
    getPlans(_fpId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改航线列表";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["plansRef"].validate(valid => {
        if (valid) {
            if (form.value.fpId != null) {
                updatePlans(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            }
            else {
                addPlans(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    }
    );
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _fpIds = row.fpId || ids.value;
    proxy.$modal.confirm('是否确认删除航线列表编号为"' + _fpIds + '"的数据项？').then(function () {
        return delPlans(_fpIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}



/** 导出按钮操作 */
function handleExport() {
    proxy.download('flightplans/plans/export', {
        ...queryParams.value
    }, `plans_${new Date().getTime()}.xlsx`)
}
import { getToken } from "@/utils/auth";

const upload = reactive({
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/common/uploadKmz",
    percent: 0,
    total: 0
});

const handleSuccess = (response, file, fileList) => {
    form.value.sourceFilePath = response.url
    form.value.sourceFileName = response.originalFilename
    console.log(form.value);
    console.log('上传成功:', response);
};

const handleError = (err, file, fileList) => {
    console.error('上传失败:', err);
};

function triggerFileInput() {
    uploadDialogVisible.value = open;
}

function confirmUpload() {
    loading1.value = true;
    form.value.hiDeptName = hiDeptName;
    addUpload(form.value)
        .then(response => {
            proxy.$modal.msgSuccess("导入成功");
            uploadDialogVisible.value = false;
            getList();
        })
        .catch(error => {
            console.error('Upload failed:', error);
        })
        .finally(() => {
            loading1.value = false;
        });
}

getList();
</script>

<style>
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 20px;
    z-index: 9999;
    /* 确保在最上层 */
}

.month-group {
    margin-bottom: 20px;
}

.card-col {
    margin-bottom: 15px;
}

.plan-card {
    height: 100%;
    transition: all 0.3s;
    font-size: 13px;
}

.plan-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header span {
    font-weight: bold;
    font-size: 14px;
}

.card-content {
    padding: 3px;
}

.card-content p {
    margin: 5px 0;
    display: flex;
    align-items: center;
}

.card-content .label {
    font-weight: bold;
    width: 80px;
    color: #606266;
    font-size: 13px;
}

.operation {
    display: flex;
}
</style>
